package com.yunji.news.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * Spring Security配置
 *
 * @author yunji
 * @since 2024-11-25
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF（因为是API接口）
            .csrf().disable()
            // 禁用Session（使用JWT）
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 配置请求权限
            .authorizeRequests()
                // 允许公开访问的端点
                .antMatchers("/", "/health", "/favicon.ico").permitAll()
                // 允许公开API访问（文章、学校、专业、分数线、配置、报名入口等）
                .antMatchers("/articles/**", "/categories/**", "/schools/**", 
                           "/majors/**", "/score-lines/**", "/config/**", "/registration-entries/**").permitAll()
                // 允许静态资源访问
                .antMatchers("/uploads/**").permitAll()
                // 管理员登录接口允许访问
                .antMatchers("/admin/auth/login", "/admin/auth/refresh", "/admin/auth/validate", "/admin/auth/logout").permitAll()
                // 其他管理员接口需要认证
                .antMatchers("/admin/**").authenticated()
                // 其他请求允许访问
                .anyRequest().permitAll()
            .and()
            // 禁用默认登录页面
            .formLogin().disable()
            // 禁用HTTP Basic认证
            .httpBasic().disable();
    }
}